package redis

import (
	"github.com/gomodule/redigo/redis"
	"github.com/mna/redisc"
	"time"
)

func InitRedisCluster(setting Setting) *Pool {
	// 建立slots -> node映射、node -> pool 映射。maxIdle与MaxActive限制的都是针对每个pool的
	// 取连接时，先按key计算slot，获取到node，然后从对应pool中获取连接
	checkSetting(&setting)

	cluster := &redisc.Cluster{
		StartupNodes: setting.Addr,
		DialOptions: []redis.DialOption{
			redis.DialConnectTimeout(setting.ConnectTimeout),
			redis.DialWriteTimeout(setting.DoWithTimeout),
			redis.DialReadTimeout(setting.DoWithTimeout),
		},
		CreatePool: func(address string, options ...redis.DialOption) (*redis.Pool, error) {
			return &redis.Pool{
				MaxIdle:     setting.MaxIdle,
				MaxActive:   setting.MaxPoolSize,
				IdleTimeout: setting.IdleTimeout,
				Wait:        true,
				Dial: func() (redis.Conn, error) {
					return redis.Dial("tcp", address, options...)
				},
				TestOnBorrow: func(c redis.Conn, t time.Time) error {
					_, err := c.Do("PING")
					return err
				},
			}, nil
		},
	}
	_ = cluster.Refresh()

	return &Pool{
		pool:    cluster,
		Name:    setting.Name,
		timeout: setting.DoWithTimeout,
		Type:    "cluster",
	}
}
